#include "dstring.h"

Status dstrassign(dstring *s, char *chars)
{
	size_t i = 0;
	char *c = chars;
	if(s->ch) free(s->ch);
	while(*(c++)) i++;
	if(!i){
		s->ch = NULL;
		s->length = 0;
	}else{
		s->ch = (char *)malloc(i * sizeof(char));
		if(!s->ch) exit(OVERFLOW);
		s->length = i;
		while(i--)
			s->ch[i] = chars[i];
	}
	return SUCCESS;
}

int dstrcmp(dstring s, dstring t)
{
	size_t i;
	for(i = 0; i < s.length && i < t.length; i++)
		if(s.ch[i] != t.ch[i])
			return s.ch[i] - t.ch[i];
	return s.length - t.length;
} 

Status dstrcat(dstring *des, dstring s1,dstring s2)
{
	size_t i;
	if(des->ch) free(des->ch);
	des->ch = (char *)malloc((s1.length + s2.length)*sizeof(char));
	if(!des->ch) exit(OVERFLOW);
	for(i = 0; i < s1.length; i++)
		des->ch[i] = s1.ch[i];
	for(i = 0; i < s2.length; i++)
		des->ch[i + s1.length] = s2.ch[i];
	des->length = s1.length + s2.length;
	return SUCCESS;
}

Status subdstr(dstring *sub, dstring s, size_t pos, size_t len)
{
	int i;
	if(pos < 0 || pos > s.length - 1 || len < 0 || len > s.length - pos)
	return ERROR;
	if(sub->ch) free(sub->ch);
	if(!len){
		sub->ch = NULL;
		sub->length = 0;
	}else{
		sub->ch = (char *)malloc(len * sizeof(char));
		if(!sub->ch) exit(OVERFLOW);
		for(i = 0; i < len; i++)
			sub->ch[i] = s.ch[pos + i];
		sub->length = len;
	}
	return SUCCESS;
}

int dstrpos_v1(dstring s, dstring p, int pos)
{
	dstring t = {NULL, 0};
	int i = pos, endp = s.length - pos - p.length;
	if(pos < 0 || pos > s.length - 1) 
		return -2;
	for(; i <= endp; i++){
		subdstr(&t, s, i, p.length);
		if(dstrcmp(p, t) == 0) return i;
	}
	return -1;
}
	
int dstrpos(dstring s, dstring p, int pos)
{
	int i = pos, j = 0;
	if(pos < 0 || pos > s.length - 1) 
		return -2;
	while(i < s.length - p.length + 1 && j < p.length){
		if(s.ch[i] == p.ch[j]){
			i++;
			j++;
		}else{
			i = i - j + 1;
			j = 0;
		}
	}
	if(j == p.length) return i - j;
	else return -1;
}
